//
//  ClubPersonInfoVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/9/2.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "ClubPersonInfoVC.h"

@interface ClubPersonInfoVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextViewDelegate>

@end

@implementation ClubPersonInfoVC
{
    UIImageView *_iconImageView;
    UITextField *_nameTF;
    UITextView *_introTV;
    UITextField *_cityTF;
    UITextField *_emailTF;
    UITextField *_phoneTF;
    UILabel *_placeHolderLabel;
    
    NSString *_imageType;
    UIImageView *_idCardView1;
    UIImageView *_idCardView2;
    int imageId;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改资料";
    self.view.backgroundColor = superBackgroundColor;
    [self initTableView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交申请" style:UIBarButtonItemStylePlain target:self action:@selector(editAction)];
    imageId = 0;
}
- (void)initTableView{
    UITableView *_tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    _tableView.backgroundColor = superBackgroundColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
}
#pragma - mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
       return 4;
    }else{
       return 3;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.backgroundColor = superBackgroundColor;
            _iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 35, 10, 70, 70)];
            _iconImageView.layer.masksToBounds = YES;
            _iconImageView.layer.cornerRadius = 8;
            _iconImageView.contentMode = UIViewContentModeScaleAspectFill;
            [_iconImageView sd_setImageWithURL:[NSURL URLWithString:[NSString readToNSDefaultsWithKey:kClubPhotoUrl]] placeholderImage:[UIImage imageNamed:@"userIcon"]];
            //imageview添加点击事件 上传头像
            _iconImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click0:)];
            [_iconImageView addGestureRecognizer:singleTap];
            
            [cell.contentView addSubview:_iconImageView];
            UILabel *noticLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 70, 20)];
            noticLb.text = @"点击更改头像";
            [noticLb setFont:[UIFont systemFontOfSize:11]];
            noticLb.textColor = [UIColor whiteColor];
            noticLb.backgroundColor = [UIColor grayColor];
            noticLb.alpha = 0.8;
            [_iconImageView addSubview:noticLb];
        }
        if (indexPath.row == 1) {
            UILabel *nameLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            nameLb.font = [UIFont systemFontOfSize:15];
            nameLb.text = @"名称";
            nameLb.textColor = Gray_Color;
            [cell.contentView addSubview:nameLb];
            _nameTF = [[UITextField alloc]initWithFrame:CGRectMake(75, 0, 200, 40)];
            _nameTF.placeholder = @"请输入俱乐部名称";
            _nameTF.text = [NSString readToNSDefaultsWithKey:kClubName];
            _nameTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_nameTF];
        }
        if (indexPath.row == 2) {
            UILabel *introLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            introLb.font = [UIFont systemFontOfSize:15];
            introLb.text = @"简介";
            introLb.textColor = Gray_Color;
            [cell.contentView addSubview:introLb];
            _introTV = [[UITextView alloc]initWithFrame:CGRectMake(70, 5, KScreenWidth - 80, 90)];
            _introTV.text = [NSString readToNSDefaultsWithKey:kClubSummary];
            _introTV.delegate = self;
            _introTV.font = [UIFont systemFontOfSize:14];
            //placeHolderLabel
            _placeHolderLabel = [[UILabel alloc]initWithFrame:CGRectMake(3, 0, 300, 30)];
            if (_introTV.text.length == 0) {
                _placeHolderLabel.text = @"输入俱乐部简介";
            }else{
                _placeHolderLabel.text = @"";
            }
            _placeHolderLabel.font = [UIFont systemFontOfSize:13];
            [_placeHolderLabel setTextColor:LightGray_Color];
            [_introTV addSubview:_placeHolderLabel];
            [cell.contentView addSubview:_introTV];
        }
        if (indexPath.row == 3) {
            UILabel *addressLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            addressLb.font = [UIFont systemFontOfSize:15];
            addressLb.text = @"城市";
            addressLb.textColor = Gray_Color;
            [cell.contentView addSubview:addressLb];
            _cityTF = [[UITextField alloc]initWithFrame:CGRectMake(75, 0, 200, 40)];
            _cityTF.placeholder = @"请输入所在地";
            _cityTF.text = [NSString readToNSDefaultsWithKey:kCity];
            _cityTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_cityTF];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            UILabel *emailLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            emailLb.font = [UIFont systemFontOfSize:15];
            emailLb.text = @"邮箱";
            emailLb.textColor = Gray_Color;
            [cell.contentView addSubview:emailLb];
            _emailTF = [[UITextField alloc]initWithFrame:CGRectMake(80, 0, 200, 40)];
            _emailTF.placeholder = @"请输入邮箱";
            _emailTF.text = [NSString readToNSDefaultsWithKey:kEmail];
            _emailTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_emailTF];
        }
        if (indexPath.row == 1) {
            UILabel *phoneLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            phoneLb.font = [UIFont systemFontOfSize:15];
            phoneLb.text = @"电话";
            phoneLb.textColor = Gray_Color;
            [cell.contentView addSubview:phoneLb];
            _phoneTF = [[UITextField alloc]initWithFrame:CGRectMake(75, 0, 200, 40)];
            _phoneTF.userInteractionEnabled = NO;
            _phoneTF.text = [NSString readToNSDefaultsWithKey:kPhone];
            _phoneTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_phoneTF];
        }
        if (indexPath.row == 2) {
            UIView *bgView1 = [[UIView alloc]initWithFrame:CGRectMake(30, 10, 120, 130)];
            bgView1.backgroundColor = superBackgroundColor;
            [cell.contentView addSubview:bgView1];
            _idCardView1 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 25, 100, 70)];
            _idCardView1.backgroundColor = superBackgroundColor;
//            _idCardView1.image = [UIImage imageNamed:@"button_add"];
            [_idCardView1 sd_setImageWithURL:[NSURL URLWithString:[NSString readToNSDefaultsWithKey:kIdCardFimgUrl]] placeholderImage:nil];
            //添加点击事件
            _idCardView1.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click1:)];
            [_idCardView1 addGestureRecognizer:singleTap];
            [bgView1 addSubview:_idCardView1];
            UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 120, 20)];
            label1.text = @"点击上传身份证正面";
            label1.textColor = Gray_Color;
            label1.textAlignment = NSTextAlignmentCenter;
            label1.font = [UIFont systemFontOfSize:13];
            [bgView1 addSubview:label1];
            
            UIView *bgView2 = [[UIView alloc]initWithFrame:CGRectMake(KScreenWidth - 150, 10, 120, 130)];
            bgView2.backgroundColor = superBackgroundColor;
            [cell.contentView addSubview:bgView2];
            _idCardView2 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 25, 100, 70)];
            _idCardView2.backgroundColor = superBackgroundColor;
//            _idCardView2.image = [UIImage imageNamed:@"button_add"];
            [_idCardView2 sd_setImageWithURL:[NSURL URLWithString:[NSString readToNSDefaultsWithKey:kIdCardBimgUrl]] placeholderImage:nil];
            //添加点击事件
            _idCardView2.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click2:)];
            [_idCardView2 addGestureRecognizer:singleTap2];
            [bgView2 addSubview:_idCardView2];
            UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 120, 20)];
            label2.text = @"点击上传身份证反面";
            label2.textColor = Gray_Color;
            label2.textAlignment = NSTextAlignmentCenter;
            label2.font = [UIFont systemFontOfSize:13];
            [bgView2 addSubview:label2];
        }
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 90;
        }
        if (indexPath.row == 1 || indexPath.row == 3) {
            return 40;
        }
        if (indexPath.row == 2) {
            return 130;
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            return 40;
        }
        else{
            return 150;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }
    return 5;
}
#pragma - mark UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length == 0) {
        _placeHolderLabel.text = @"输入俱乐部简介";
    }else{
        _placeHolderLabel.text = @"";
    }
}
//选择手机相册的照片
- (void)click0:(UITapGestureRecognizer *)sender{
    imageId = 0;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self LocalPhoto];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self takePhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:albumAction];
    [alert addAction:photoAction];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)click1:(UITapGestureRecognizer *)sender{
    imageId = 1;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self LocalPhoto];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self takePhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:albumAction];
    [alert addAction:photoAction];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)click2:(UITapGestureRecognizer *)sender{
    imageId = 2;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self LocalPhoto];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self takePhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:albumAction];
    [alert addAction:photoAction];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
//从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}
//拍照
-(void)takePhoto{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else {
    }
}
//取出图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //1.退出图片选择器
    [picker dismissViewControllerAnimated:YES completion:nil];
    //2.取出图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (imageId == 0) {
        _imageType = @"1";
        [_iconImageView setImage:image];
    }
    if (imageId == 1) {
        _imageType = @"2";
        [_idCardView1 setImage:image];
    }
    if (imageId == 2) {
        _imageType = @"3";
        [_idCardView2 setImage:image];
    }
    NSData *dataAvatar = UIImageJPEGRepresentation(image,0.5);
    [self uploadAvatarWithImage:dataAvatar];
    [self uploadAvatarWithClubImage:dataAvatar];
}

//上传头像至服务器
- (void)uploadAvatarWithClubImage:(NSData *)imageAvatarData{
    //参数
    NSDictionary *parameters = @{
                                 @"clubId": [NSString readToNSDefaultsWithKey:kClubId],
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/club/imgUpload.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageAvatarData name:@"file" fileName:[self getImgFileName] mimeType:@"image/png"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];
}
- (void)uploadAvatarWithImage:(NSData *)imageAvatarData{
    //参数
    NSDictionary *parameters = @{
                                 @"id": [NSString readToNSDefaultsWithKey:kClubUserID],
                                 @"imgType": _imageType,
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/user/imgUpload.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageAvatarData name:@"file" fileName:[self getImgFileName] mimeType:@"image/png"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *imgUrlDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"<<<<<%@",imgUrlDic);
        NSString *error = imgUrlDic[@"code"];
        if (![imgUrlDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //请求成功
            NSString *_imgUrl = imgUrlDic[@"imgUrl"];
            NSLog(@"<<<%@",_imgUrl);
            //获取当前时间
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYYMMddHHmmssSSS"];
            NSString *dateString = [dateFormatter stringFromDate:currentDate];
            //头像和身份证保存
            if ([_imageType isEqualToString:@"1"]) {
                _imgUrl = [NSString stringWithFormat:@"%@%@%@",_imgUrl, @"?",dateString];
                [_imgUrl saveToNSDefaultsWithKey:kClubPhotoUrl];
            }
            if ([_imageType isEqualToString:@"2"]) {
                _imgUrl = [NSString stringWithFormat:@"%@%@%@",_imgUrl, @"?",dateString];
                [_imgUrl saveToNSDefaultsWithKey:kIdCardFimgUrl];
            }
            if ([_imageType isEqualToString:@"3"]) {
                _imgUrl = [NSString stringWithFormat:@"%@%@%@",_imgUrl, @"?",dateString];
                [_imgUrl saveToNSDefaultsWithKey:kIdCardBimgUrl];
            }
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
        }
       
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请检查网络问题"];
    }];
}
- (NSString *)getImgFileName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    return fileName;
}
//修改个人资料
- (void)editAction{
    //参数
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setValue:[NSString readToNSDefaultsWithKey:kClubId] forKey:@"clubID"];
    [parameters setValue:_nameTF.text forKey:@"clubName"];
    [parameters setValue:@"2016.09.10" forKey:@"signTime"];
    [parameters setValue:_introTV.text forKey:@"clubSummary"];
    [parameters setValue:_cityTF.text forKey:@"city"];
    [parameters setValue:_emailTF.text forKey:@"email"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/club/editClubInfo.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSDictionary *_responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"请求成功"];
            [_responseDic[@"object"][@"club"][@"clubName"] saveToNSDefaultsWithKey:kClubName];
            [_responseDic[@"object"][@"club"][@"clubSummary"] saveToNSDefaultsWithKey:kClubSummary];
            [_responseDic[@"object"][@"user"][@"city"] saveToNSDefaultsWithKey:kCity];
            [_responseDic[@"object"][@"user"][@"email"] saveToNSDefaultsWithKey:kEmail];
            
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
